<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0" />
</head>
<body>

<input type="text" id="msg" value='{"action":"user/offline","method":"response","msg":"22222","items":[]}'> <button onclick="sendmsg()">发送消息</button>
</body>
<script>
    let ws = new WebSocket("wss://cupdefense.playone.cn/wss");//这种访问方式需要nginx配置

    ws.onopen = function() {
        console.log("连接成功");
        ws.send('hello,thinkphp');
        console.log("给服务端发送一个字符串：hello,thinkphp");
    };
    ws.onmessage = function(e){
        // console.log(e);
        //e.data 的数据格式也是字符串，手动解析这些数据才能得到其他格式的数据。
        const _data = JSON.parse(e.data);
        console.log(e.data,_data);
    }

    //当客户端收到服务端发送的关闭连接请求时，触发onclose事件
    ws.onclose = function(e){
        console.log("close");
    }

    //如果出现连接、处理、接收、发送数据失败的时候触发onerror事件
    ws.onerror = function(error){
        console.log(error);
    }
    function sendmsg(){
        let msg = document.getElementById("msg").value;
        console.log('发送：'+msg);
        ws.send(msg);
    }
</script>
</html>